package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/*
/*  代表需要拦截的请求  所有请求全部拦截
            WebFilter  在请求访问到controller 之前的方法    用来筛选请求
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)request1;
        HttpServletResponse response = (HttpServletResponse)response1;
        //A. 获取本次请求的URI
        String uri = request.getRequestURI();
        //B. 判断本次请求, 是否需要登录, 才可以访问
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/upload",
                "/user/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/order/notifyAll"
        };
        //2、判断本次请求是否需要处理
        if(check(urls, uri)){//代表是登录请求
            //问题，所有的静态资源，应该都不被拦截
            //C. 如果不需要，则直接放行
            chain.doFilter(request,response);
            return;
        }
        //D. 判断登录状态，如果已登录，则直接放行
        HttpSession session = request.getSession();
        Long employee = (Long) session.getAttribute("employee");
        Long user = (Long) session.getAttribute("user");
        //E. 如果未登录, 则返回未登录结果
        if(employee != null ){ //没有登录，并且请求不能放行
            //怎么跳转到登录页面
            //response.sendRedirect("/backend/page/login/login.html");
            Long empId = (Long) request.getSession().getAttribute("employee");

            BaseContext.setCurrentId(empId);
            chain.doFilter(request,response);
            return;
        }
        if(user!=null){
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            chain.doFilter(request,response);
            return;
        }

        //放行 并且存储到ThreadLocal中
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
